package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;

/**
 * Connection to the templates table
 * 
 * Performs DAO operations for the templates table in the database
 * @author Sukhjinder K. Narula
 * @since June 2013
 * @version $Revision: 1.0 $
 */
public class TemplateSqlDao implements TemplateDao {
	
	 
	// Connection
	private Connection conn;
    
    /**
     * Constructor
     * @param conn connection object for database
     */
    public TemplateSqlDao(Connection conn) {
		this.conn = conn;
	}
    
    /**
     * Creates a new entry and returns the ID
     * @param properties 
    
     * @return int
     * @throws DaoException
     * @throws ModelException  * @see dao.TemplateDao#create(HashMap<String,String>)
     */
    public int create(HashMap<String, String> properties) throws DaoException{
    	
    	int toReturn = -1;
    	try {
    		String sql = "INSERT INTO templates (UserId, Title, Body) VALUES (?, ?, ?) ;";
	    	PreparedStatement statement = conn.prepareStatement(sql);
	    	statement.setInt(1, Integer.valueOf(properties.get("UserId")));
	    	statement.setString(2, properties.get("Title"));
	    	statement.setString(3,properties.get("Body"));
	    	statement.executeUpdate();
	    	Statement st = conn.createStatement();
        	ResultSet generatedKeys = st.executeQuery("SELECT seq FROM sqlite_sequence WHERE name = 'templates' ;");
        	if (generatedKeys.next()) {
        	    toReturn = generatedKeys.getInt("seq");
        	}
    	} catch (SQLException e){
    		throw new DaoException(e.getMessage());
    	}
    	return toReturn;
    }
    
    /**
     * Loads a template row given ID
    
    
    
     * @param Id int
     * @return properties * @throws DaoException
     * @throws ModelException  * @see dao.TemplateDao#load(int)
     */
    public HashMap<String, String> load(int Id) throws DaoException{
    	
    	HashMap<String, String> toReturn = null;
    	try {
	    	String sql = "SELECT * FROM templates WHERE Id = ? LIMIT 1; ";
	    	PreparedStatement statement = null; 
	    	statement = conn.prepareStatement(sql);
	    	statement.setInt(1, Id);
	    	ResultSet rs = statement.executeQuery();
	    	toReturn = new HashMap<String, String>();
	    	while (rs.next()) {
	    		toReturn.put("Id", String.valueOf(Id));
	    		toReturn.put("UserId", rs.getString("UserId"));
	    		toReturn.put("Title", rs.getString("Title"));
	    		toReturn.put("Body", rs.getString("Body"));
	    	}
    	} catch (SQLException e){
    		throw new DaoException(e.getMessage());
    	}
    	return toReturn;
    }

    /**
     * Updates a template
     * @param properties
    
     * @throws DaoException
     * @throws ModelException  * @see dao.TemplateDao#update(HashMap<String,String>)
     */
    public void update(HashMap<String, String> properties) throws DaoException {
    	
    	try {
    		String sql = "UPDATE templates SET Title = ?, Body = ?  WHERE Id = ?; ";
	    	PreparedStatement statement = conn.prepareStatement(sql);
	    	statement.setString(1, properties.get("Title"));
	    	statement.setString(2, properties.get("Body"));
	    	statement.setInt(3, Integer.valueOf(properties.get("Id")));
	    	statement.executeUpdate();
    	} catch (SQLException e){
    		throw new DaoException(e.getMessage());
    	}
    }

	/**
	 * Deletes a user row, given the id
	
	
	 * @param Id int
	 * @throws DaoException
	 * @throws ModelException  * @see dao.TemplateDao#delete(int)
	 */
	public void delete(int Id) throws DaoException {
		
		try {
	    	String sql = "DELETE FROM templates WHERE Id = ? ; ";
	    	PreparedStatement statement = conn.prepareStatement(sql);
	    	statement.setInt(1, Id);
	    	statement.executeUpdate();
    	} catch (SQLException e){
    		throw new DaoException(e.getMessage());
    	}
	}
	
	/**
	 * Given the userId, returns all the templates
	 * @param userId
	
	
	 * @return HashMap * @throws DaoException * @see dao.TemplateDao#findByUserId(int)
	 */
	public HashMap<Integer, String[]> findByUserId(int userId) throws DaoException {

		HashMap<Integer, String[]> properties = new HashMap<>();
		int index = 0, key;
        PreparedStatement statement;
		try {
			statement = conn.prepareStatement("SELECT * FROM templates WHERE UserId = ? ORDER BY Title ;");
			statement.setString(1, String.valueOf(userId));
	        ResultSet rs = statement.executeQuery();
        	while (rs.next()){
        		String templateProperties[] = new String[3];
        		index = 0;
        		key = rs.getInt(1);
        		templateProperties[index++] = rs.getString(2);
        		templateProperties[index++] = rs.getString(3);
        		templateProperties[index++] = rs.getString(4);
        		properties.put(key, templateProperties);
        	}                   
	        rs.close();  
		} catch (SQLException e) {
			throw new DaoException(e.getMessage());
		}                  
        return properties;
	}
	
	/**
	 * Given a user id, delete all the templates
	 * @param userId
	
	 * @throws DaoException
	 * @throws ModelException  * @see dao.TemplateDao#deleteByUserId(int)
	 */
	public void deleteByUserId(int userId) throws DaoException {
		
		try {
	    	String sql = "DELETE FROM templates WHERE UserId = ? ; ";
	    	PreparedStatement statement = conn.prepareStatement(sql);
	    	statement.setInt(1, userId);
	    	statement.executeUpdate();	
    	} catch (SQLException e){
    		throw new DaoException(e.getMessage());
    	}
		
	}
	
	/**
	 * Given a set of template ids, delete all the templates
	
	
	 * @param templateIds Set<Integer>
	 * @throws DaoException
	 * @throws ModelException  * @see dao.TemplateDao#deleteByTemplateIds(Set<Integer>)
	 */
	public void deleteByTemplateIds(Set<Integer> templateIds) throws DaoException {
		
		try {
			String sql = "DELETE FROM templates WHERE TemplateId IN ( "+ StringUtils.join(templateIds, " , ") +" ) ; ";
	    	Statement statement = conn.createStatement();
	    	statement.execute(sql);
    	} catch (SQLException e){
    		throw new DaoException(e.getMessage());
    	}
		
	}

}